package com.guo.xiao.bing.controller;

import com.github.pagehelper.PageInfo;
import com.guo.xiao.bing.entity.Project;
import com.guo.xiao.bing.entity.ProjectType;
import com.guo.xiao.bing.entity.User;
import com.guo.xiao.bing.service.ProjectService;
import com.guo.xiao.bing.service.ProjectTypeService;
import com.guo.xiao.bing.util.Encryption;
import com.guo.xiao.bing.vo.ProjectVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("project")
public class ProjectController {

    @Autowired
    ProjectService projectService;
    @Autowired
    ProjectTypeService projectTypeService;

    @RequestMapping(value = "", method = RequestMethod.GET)
    public String list(Model model) {
        List<Project> projectTypes = projectService.find();
        model.addAttribute("type", projectTypes);
        return "project/list";
    }

    @RequestMapping(value = "/{page}", method = RequestMethod.GET)
    public String pageUser(@PathVariable Integer page, Model model) {
        PageInfo<Project> userPageInfo = projectService.pageFindProjectsByExample(page);
        model.addAttribute("page", userPageInfo);
        return "project/list";
    }

    @RequestMapping(value = "add", method = RequestMethod.GET)
    public String add(HttpSession session, Model model) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/user/login";
        }
        List<ProjectType> projectTypes = projectTypeService.find();
        model.addAttribute("projectTypes", projectTypes);
        return "project/add";
    }


    @RequestMapping(value = "add", method = RequestMethod.POST)
    public String add(HttpSession session, Model model, @ModelAttribute Project project) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/user/login";
        }

        StringBuilder sb = new StringBuilder("https://www.gravatar.com/avatar/");
        sb.append(Encryption.MD5(project.getContent()));
        sb.append("?d=identicon");
        project.setPic(sb.toString());

        projectService.save(project);
        return "redirect:/project/1";
    }



    @RequestMapping(value = "del/{id}", method = RequestMethod.GET)
    public String del(@PathVariable Integer id, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/user/login";
        }
        projectService.delete(id);
        return "redirect:/project/1";
    }

}
